package com.lening.organization.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lening.common.base.BaseController;
import com.lening.common.util.ExportUtils;
import com.lening.common.util.ImportUtil;
import com.lening.common.web.Result;
import com.lening.organization.dto.PeopleDTO;
import com.lening.organization.dto.PostRoleDTO;
import com.lening.organization.po.People;
import com.lening.organization.service.PeopleService;
import com.lening.organization.service.impl.PeopleServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/people")
public class PeopleController extends BaseController<People, PeopleDTO, PeopleServiceImpl> {

    @Resource
    private PeopleService peopleService;

    @GetMapping(value = "/findPeople")
    public Page<People> findPeople(Integer pageNum, Integer pageSize, Page<PeopleDTO> peopleDTO) {
        Page<People> peopleList = peopleService.findPeople(pageNum, pageSize, peopleDTO);
        return peopleList;
    }

    /**
     * 下载数据模板
     * 模块的原因是根据模板填写数据，上传的数据才不会出差错
     * 为什么这样？具体原因你懂的
     */

    @Transactional
    @GetMapping("/download/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 调用接口，并传入空数据，在导出已经做出判断，
        // 说明这个接口是下载模板，不会往表格里面写数据
        ExportUtils.exportData(response, null , People.class);
    }



    /**
     * 导出
     */

    @Transactional
    @GetMapping("/export")
    public void exportRole(HttpServletResponse response) throws IOException {
        // 数据库获取数据，Mybatis-plus的方法，不知道的可以学习学习MP
        List<People> userDOList = peopleService.list();
        // 调用导出工具类的方法，传入对应的参数，简单吧
        ExportUtils.exportData(response, userDOList , People.class);
    }

    /**
     * 导入
     */

    @Transactional
    @PostMapping("/import")
    public void importsEntity(@RequestParam("file") MultipartFile file) throws Exception {
        // 调用ImportUtil工具类来获取实体对象列表
        // 传入接口获取的文件和实体类，就可以获取到数据，简单吧
        List<People> entities = ImportUtil.importEntities(file, People.class);
        // 在这里处理导入数据的逻辑
        for (People entity : entities) {
            // 执行对数据的操作，例如保存到数据库等
            System.out.println("导入的数据：" + entity);
            boolean save = peopleService.save(entity);
            if (save) {
                System.out.println("插入  " + entity + "   成功！");
            } else {
                System.out.println("插入  " + entity + "   失败！");
            }
        }
    }

    @PostMapping("/addUserRole")
    public Result addUserRole(@RequestBody PostRoleDTO postRoleDTO){
        peopleService.addUserRole(postRoleDTO);
        return Result.ok(null);
    }


}
